<template>
  <el-form label-position="top" label-width="80px" :model="adForm" :rules="adFormRules"
           ref="adForm">
    <basic-container ref="3-1">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>广告名称</div>
        </div>
      </div>
      <el-form-item label="" prop="adName">
        <el-input size="mini" v-model="adForm.adName" placeholder="请输入内容"></el-input>
      </el-form-item>
    </basic-container>
    <basic-container ref="3-2">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>广告发布者身份</div>
        </div>
      </div>
      <el-form-item label="">
        <el-switch
          v-model="adForm.sparkAdsSwitch"
          :active-color="activeColor"
          :inactive-color="inactiveColor"
          disabled
          active-text="使用 TikTok 账号投放 Spark Ads "
          inactive-text="">
        </el-switch>
        <div class="row-tips">申请使用 TikTok 账号个人帖子的权限，然后使用该账号的身份投放广告。</div>
      </el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="adForm.identityId" placeholder="请选择身份">
          <el-option
            v-for="item in identityList"
            :key="item.id"
            :label="item.displayName"
            :value="item.identityId">
            <span style="float: left"><el-avatar :size="30" :src="item.identityIcon"></el-avatar></span>
            <span style="float: right"> {{ item.displayName }}
                      </span>
          </el-option>
        </el-select>
        <el-button style="margin-left: 5px" type="text" icon="el-icon-refresh-right"
                   @click="getIdentityList(true)"
                   v-loading="editIdentityListLoading"></el-button>
        <el-dialog
          title="添加自定义身份名称"
          :visible.sync="addIdentityDialog"
          :close-on-click-modal="false"
          :modal-append-to-body="false"
          :modal="false"
          width="300px">
          <el-form :model="identityForm" ref="identityForm" label-width="0px" @submit.native.prevent>
            <el-form-item
              prop="value"
              :rules="[{ required: true, message: '身份名称不能为空',trigger: 'blur'},]">
              <el-upload
                style="display:inline-block;"
                class="identity-upload"
                action="#"
                :http-request="uploadQiniuCloud"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false"
                list-type="picture">
                <el-avatar :size="50" :src="logoUrl" :key="logoUrl"></el-avatar>
              </el-upload>
              &nbsp;
              <el-input v-model="identityForm.value" style="width: 75%"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
                    <el-button @click="addIdentityDialog = false">取 消</el-button>
                    <el-button type="primary" @click="addIdentity" v-loading="addIdentityLoading">确 定</el-button>
                  </span>
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="text" icon="el-icon-plus" @click="addIdentityDialog = true">添加自定义身份
        </el-button>
      </el-form-item>
    </basic-container>
    <basic-container ref="3-3">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>创意素材</div>
        </div>
      </div>
      <aco-ad-edit
        v-if="adGroup.creativeMaterialMode === 'DYNAMIC'"
        :creatives="acoCreatives"
        :docs="acoAdTexts"
        :ctas="acoCTAs"
        :call-to-action-list="callToActionList"
        :call-to-action-type.sync="adForm.callToActionType"
        :text-data="textData"
        :offer-id="offerId"
        @changeAcoCreatives="changeAcoCreatives"
        @changeCTAVals="changeCTAVals"
        @changeDocs="changeDocs"
        ref="acoEditDrawer"
      ></aco-ad-edit>
      <template v-else>
        <el-form-item :label="adForm.adFormat==='SINGLE_VIDEO'?'视频':'图片'">
          <template v-if="adForm.adFormat==='SINGLE_VIDEO'">
            <div style="display: flex">
              <div style="margin-right: 15px;cursor: pointer">
                <el-image fit="cover" :src="editAdCreatives.thumbnailUrl" style="width: 360px;height: 640px;"
                          @click="handlePreview(editAdCreatives)"/>
              </div>
              <div>
              </div>
            </div>
          </template>
          <template v-else>
            <div style="display: flex;cursor: pointer">
              <div>
                <el-image fit="cover" :src="editAdCreatives.creativeUrl" style="width: 360px;height: 640px;"
                          @click="handlePreview(editAdCreatives)"/>
              </div>
              <div>
                <!--                      <p>广告名称:{{ adForm.adName }}</p>-->

              </div>
            </div>
          </template>
          <span>{{ editAdCreatives.name }}</span>
          <el-button type="text" size="mini" icon="el-icon-edit"
                     @click="handleOpenEditCreative">更新
          </el-button>
          <creative-card-preview v-model="assetPreview" :media-preview="previewCreative">
          </creative-card-preview>
          <creative-drawer :visible.sync="editFromStroeDrawer" v-if="editFromStroeDrawer"
                           @get-creative="handleChangeAdCreative"></creative-drawer>
        </el-form-item>
        <el-form-item label="广告文案">
          <el-autocomplete
            size="mini"
            v-model="adForm.adText"
            :fetch-suggestions="queryCreativeTextSearch"
            placeholder="请输入内容"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="目标页">
          <div>
            <el-radio v-model="adForm.callToActionType" label="1">动态优选</el-radio>
          </div>
          <div>
            <el-radio v-model="adForm.callToActionType" label="0">标准</el-radio>
          </div>
          <el-collapse-transition>
            <div v-show="adForm.callToActionType === '0'">
              <el-select v-model="adForm.callToAction" placeholder="请选择" size="mini">
                <el-option v-for="item in callToActionList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </div>
          </el-collapse-transition>
        </el-form-item>
      </template>
    </basic-container>
    <basic-container ref="3-5" v-if="campaign.campaignAppProfilePageState ==='ON'">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>目标页</div>
        </div>
      </div>
      <el-form-item label="应用介绍页" prop="pageId" ref="ad-pageId">
        <el-select size="mini" v-model="adForm.pageId" placeholder="请选择应用介绍页" v-loading="landingPageLoading"
                   @change="handleChangeLandingPage">
          <el-option
            v-for="item in landingPageList"
            :key="item.value"
            :label="item.label+'  ID:'+item.value"
            :value="item.value">
          </el-option>
        </el-select>
        <!--<el-button style="margin-left: 5px" type="text" icon="el-icon-refresh-right"-->
        <!--           @click="getLandingPageList" v-loading="landingPageLoading"></el-button>-->
        <div>
          <el-image
            v-show="adForm.imageUrl !== ''"
            style="width: 100px; height: 100px"
            :src="adForm.imageUrl"
            fit="cover"></el-image>
        </div>
      </el-form-item>
    </basic-container>
    <basic-container ref="3-4">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>检测</div>
        </div>
      </div>
      第三方监测设置
      <el-form-item label="展现监测URL">
        <el-input size="mini" v-model="adForm.impressionTrackingUrl"></el-input>
      </el-form-item>
      <el-form-item label="点击监测URL">
        <el-input size="mini" v-model="adForm.clickTrackingUrl" disabled></el-input>
      </el-form-item>
    </basic-container>
  </el-form>
</template>

<script>
import * as qiniuTools from "@/util/qinnu_upload";
import {
  createTtIdentity,
  getAcoDetail, getLandingPageList,
  getTextList,
  getTtIdentity
} from "@/api/campaign-management/campaign-management";
import {selectone} from "@/api/offer/creativeperformance";
import CreativeDrawer from "@/views/campaign-management/components/CreativeDrawer";
import CreativeCardPreview from "@/components/CreativeCardPreview/CreativeCardPreview";
import _ from "lodash";
import {getCallToActionList} from "@/util/beetles";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {mapState} from "vuex";
import AcoAdEdit from "@/views/campaign-management/components/AcoAdEdit";

export default {
  name: "AdForm",
  components: {
    CreativeDrawer,
    CreativeCardPreview,
    CsDrawerContainer,
    AcoAdEdit
  },
  props: {
    options: {
      type: Object
    },
    platformAppId: {
      type: String
    },
    adGroup: {
      type: Object
    },
    campaign: {
      type: Object
    },
    isOriginAccount: {
      type: Boolean,
      default: false
    },
    currentAccountId: {
      type: String
    },
  },
  computed: {
    ...mapState({
      offerId: state => state.user.offer,
    }),
  },
  data() {
    return {
      adForm: {
        // 广告名字
        adName: '',
        // Spark Ads
        sparkAdsSwitch: false,
        // 发布者身份
        identityId: '',
        // 批量实现类型
        autoCreateType: 1,
        // 素材格式
        adFormat: 'SINGLE_VIDEO',
        // 动态优选
        callToActionType: 1,
        // 展示动态监测
        impressionTrackingUrl: '',
        // 点击监测url
        clickTrackingUrl: '',
        // 素材列表
        creativeList: [],
        // 单文案
        adText: '',
        // 行动引导文案
        callToAction: 'DOWNLOAD_NOW',
        adIdentityName: '',
        creativeId: '',
        platformId: '',
        imageUrl: '',
        landingPageUrl: '',
        pageId: '',
        creativeUrl: '',
        creativeType: 1
      },
      activeColor: "#13ce66",
      inactiveColor: "#ccc",
      //ad表单校验
      adFormRules: {
        adName: [{required: true, message: '请输入广告名称', trigger: 'blur'}],
        identityId: [{required: true, message: '请选择发布者身份', trigger: 'change'}],
        pageId: [{required: true, message: '请选择应用介绍页', trigger: 'change'}]
      },
      identityList: [],
      identityForm: {
        value: ''
      },
      addIdentityDialog: false,
      addIdentityLoading: false,
      editAdCreatives: {
        thumbnailUrl: '',
        creativeUrl: ''
      },
      logoUrl: '',
      editFromStroeDrawer: false,
      assetPreview: false,
      previewCreative: null,
      callToActionList: [],
      textData: [],
      editIdentityListLoading: false,
      acoCreatives: [],
      acoAdTexts: [],
      acoCTAs: [],
      landingPageList: [],
      landingPageLoading: false
    }
  },
  async created() {
    this.callToActionList = getCallToActionList()
    await this.initOption()
    this.getIdentityList()
    if (this.campaign.campaignAppProfilePageState === 'ON') {
      await this.getLandingPageList()
      this.handleChangeLandingPage(this.adForm.pageId)
    }
    getTextList(this.offerId).then(res => {
      this.textData = res.data.data;
    });
  },
  methods: {
    uploadQiniuCloud(file) {
      const that = this
      const fileData = qiniuTools.getFileData(file)
      const callback = {
        next(res) {
        },
        error(err) {
          this.$message.error("上传图片失败! err => " + err);
        },
        complete(res) {
          const url = 'http://' + fileData.server + '/' + res.key
          that.$set(that, 'logoUrl', url)
          // that.logoUrl = url
        }
      }
      const uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },
    // 限制上传图片类型
    beforeAvatarUpload(file) {
      var img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img === 'jpg'
      const suffix2 = img === 'png'
      const suffix3 = img === 'jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!suffix && !suffix2 && !suffix3) {
        this.$message.error("只能上传图片！");
        return false
      }
      // 可以限制图片的大小
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return suffix || suffix2 || suffix3
    },
    initOption() {
      this.adForm.adName = this.options.adName
      this.adForm.identityId = this.options.identityId
      this.adForm.creativeId = this.options.creativeId
      this.adForm.adFormat = this.options.adFormat
      this.adForm.callToActionType = this.options.callToActionType
      this.adForm.impressionTrackingUrl = this.options.impressionTrackingUrl
      this.adForm.clickTrackingUrl = this.options.clickTrackingUrl
      this.adForm.adText = this.options.adText
      this.adForm.callToAction = this.options.callToAction
      this.adForm.adIdentityName = this.options.adIdentityName
      this.adForm.platformId = this.options.platformId
      this.adForm.pageId = this.options.pageId
      this.adForm.landingPageUrl = this.options.landingPageUrl
      this.adForm.creativeUrl = this.options.creativeUrl
      this.adForm.creativeType = this.options.creativeType
      this.adForm.imageUrl = this.options.imageUrl
      if (this.adGroup.creativeMaterialMode === 'DYNAMIC' && !this.adGroup.isEditAd) {
        getAcoDetail({adGroupId: this.options.adGroupId}).then(res => {
          this.acoCreatives = res.data.data.creatives
          this.acoAdTexts = res.data.data.adTextList
          this.acoCTAs = _.compact(res.data.data.callToAction)
          this.adForm.oldAcoCreatives = _.cloneDeep(this.adForm.acoCreatives)
          this.adForm.oldAcoAdTexts = _.cloneDeep(this.adForm.acoAdTexts)
          this.adForm.oldAcoCTAs = _.cloneDeep(this.adForm.acoCTAs)
          this.adForm.adIds = res.data.data.adIds
        })
      } else {
        this.acoCreatives = this.adGroup.acoCreatives
        this.acoAdTexts = this.adGroup.acoAdTexts
        this.acoCTAs = this.adGroup.acoCTAs
        this.getCreativeById(this.adForm.creativeId)
      }
    },
    async getIdentityList(refresh) {
      this.editIdentityListLoading = true
      const {data: res} = await getTtIdentity({
        refresh: refresh || false,
        platformId: this.adForm.platformId,
        platformAppId: this.options.appId
        // platformAppId: '6853999917673742342'
      }).finally(() => {
        this.editIdentityListLoading = false
      })
      this.identityList = res.data
      if (!this.isCurrentAccount) {
        this.identityList.push({displayName: this.options.adIdentityName, identityId: this.options.adIdentityName})
      }
    },
    async getCreativeById(creativeId) {
      const {data: res} = await selectone(creativeId)
      this.editAdCreatives = res;
    },
    handleOpenEditCreative() {
      this.editFromStroeDrawer = true

    },
    // 格式化素材类型
    formatterCreativeType(row, column, cellValue, index) {
      if (cellValue == 0) {
        return '图片'
      } else {
        return '视频'
      }
    },
    addIdentity() {
      if (this.addIdentityLoading) return
      this.$refs.identityForm.validate(async valid => {
        if (!valid) return
        this.addIdentityLoading = true
        const {data: res} = await createTtIdentity({
          platformId: this.options.platformId,
          platformAppId: this.platformAppId,
          displayName: this.identityForm.value,
          logoUrl: this.logoUrl
        }).finally(() => {
          this.addIdentityLoading = false
        })
        // this.identityList.push(res.data)
        this.$message.success('添加自定义身份成功')
        await this.getIdentityList()
        this.identityForm.value = ''
        this.addIdentityDialog = false
      })
    },
    handlePreview(row) {
      this.previewCreative = _.cloneDeep(row)
      this.assetPreview = true
    },
    // 文案输入框查询
    queryCreativeTextSearch(queryString, cb) {

      // var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(this.transformCreativeText(queryString));
    },
    transformCreativeText(queryString) {
      if (queryString === '') {
        return this.textData.map(item => {
          return {value: item.text}
        })
      } else {
        return this.textData.filter(item => {
          const input = queryString.toLowerCase()
          const text = item.text.toLowerCase()
          return text.includes(input)
        }).map(item => {
          return {value: item.text}
        })
      }
    },
    handleChangeAdCreative(creative) {
      this.editAdCreatives = creative
      this.adForm.creativeId = creative.id
      this.adForm.creativeType = creative.type
      this.adForm.creativeUrl = creative.creativeUrl
      this.adForm.adFormat = creative.type == 0 ? 'SINGLE_IMAGE' : 'SINGLE_VIDEO'
    },
    changeAcoCreatives(val) {
      // this.$set(this.adForm,'acoCreatives', val)
      this.acoCreatives = val
    },
    changeCTAVals(val) {
      this.acoCTAs = val
    },
    changeDocs(val) {
      this.acoAdTexts = val
    },
    handleChangeLandingPage(val) {
      const page = this.landingPageList.find(item => item.value === val)
      this.adForm.landingPageUrl = page.landingPageUrl
      this.adForm.imageUrl = page.imageUrl
    },
    // 获取落地页
    async getLandingPageList() {
      // if (this.landingPageLoading) return
      this.landingPageLoading = true
      const {data: res} = await getLandingPageList(this.currentAccountId).finally(() => {
        this.landingPageLoading = false
      })
      this.landingPageList = res.data
    },
  }
}
</script>

<style scoped>

</style>
